<template>
	<view class="chat">
		<!-- 顶部标题 -->
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="content">智能互动</block>
		</cu-custom>
		<scroll-view :style="{height: `${windowHeight-inputHeight -180}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''">
						<!-- 文字内容 -->
						<view class="content right">
							{{item.userContent}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.image">
						</image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != ''">
						<!-- 头像 -->
						<image class="avatar" :src="item.image">
						</image>
						<!-- 文字内容 -->
						<view v-if="item.botArrary" class="content left">
							<view v-for="(matter,index) in item.botArrary">
								<view class="subjetItem" @tap.stop="searchSubItem(matter.itemSubjectId)" > {{matter.itemSubjectName}} </view>
							</view>
						</view>
						<view v-else-if="item.subItemArrary" class="content left">
							<view v-for="(subItem,index) in item.subItemArrary">
								<view class="subjetItem" @tap.stop="toWork(subItem.itemBusinessId)" > {{subItem.itemBusinessName}} </view>
							</view>
						</view>
						<view v-else>
							<view class="content left">
								{{item.botContent}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部消息发送栏 -->
		<view class="chatBottom" :style="{height: `${inputHeight}rpx`}">
			<view class="rowCenter" style="padding: 10rpx; 20rpx">
				<view class="allCenter workModel" @click="gotoCustomer()">转人工</view>
				<view class="allCenter workModel">办事指南</view>
			</view>
			<view class="rowCenter ">
				<view class="inputText">
					<textarea class="inputStyle" v-model="chatMsg" maxlength="30" confirm-type="send"
						@input="handleInput" @confirm="handleSend" :placeholder=placeholder
						placeholder-class="placeholder" :show-confirm-bar="false" :adjust-position="false"
						@linechange="sendHeight" @focus="focus" @blur="blur" auto-height></textarea>
					<view style="display: flex;justify-content: end; font-size: 22rpx; color: #8799a3;">
						{{keywordNumber}}/30
					</view>
				</view>
				<view class="allCenter send-btn" @click="handleSend()">发送</view>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				keyboardHeight: 0, //键盘高度
				bottomHeight: 0, //底部消息发送高度
				scrollTop: 0, //滚动距离
				textareaHeight: 80, // 初始高度
				userId: '',
				chatMsg: "", //发送的消息
				botMsg: "", //机器人回复消息
				placeholder: '请输入您想咨询的关键词',
				keywordNumber: 0, // 输入文字长度
				askSubjectUrl: '/appointment/qa/askSubject',//智能问答接口
				getSubItemUrl: '/appointment/qa/getBySubjectId',//查询子项接口
				customer: "../../static/icon/customer.png",//客服头像地址
				askUser: "../../static/icon/askUser.png",// 用户头像地址
				msgList: [{
						botContent: "你好啊,请问我有什么可以帮助你的吗？",
						userContent: "",
						image: "../../static/icon/customer.png"
					},
					{
						botContent: "",
						userContent: "",
						image: "../../static/icon/askUser.png",
						botArrary: [],
						subItemArrary:[]
					},
				]
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onLoad() {
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = this.rpxTopx(res.height)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
		},
		onUnload() {
			// uni.offKeyboardHeightChange()
		},
		methods: {
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			/**计数初始高度**/
			calculateTextareaHeight() {
				const lineHeight = 20; // 输入框一行的高度
				const maxRows = 5; // 最大显示行数
				const height = Math.min(lineHeight * maxRows, lineHeight * Math.ceil(Number(this.placeholder.length) /
					15));
				// 设置 textarea 的高度
				this.textareaHeight = height;
			},

			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.rowCenter').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			//跳转人工客服
			gotoCustomer() {
				uni.navigateTo({
					url: "/pages/customerService/customerService"
				})
			},
			//监听输入的字数
			handleInput(e) {
				const cursorPosition = e.detail.cursor;
				const value = e.detail.value;
				const length = value.length;
				this.keywordNumber = length;
			},

			// 发送消息
			handleSend() {
				//如果消息不为空
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					let obj = {
						botContent: "",
						userContent: this.chatMsg,
						image: this.askUser
					}
					this.msgList.push(obj);
					this.$http.post(this.askSubjectUrl, {
						issue: this.chatMsg
					}).then(res => {
						if (res.data.code == '200') {
							if (res.data.message == '未找到相关答案，可尝试转人工服务') {
								this.botMsg = res.data.result;
								obj = {
									botContent: this.botMsg,
									userContent: "",
									image: this.customer
								}
								this.msgList.push(obj);
							} else {
								let askList = res.data.result;
								obj = {
									botContent: "主项数据",
									userContent: "",
									botArrary: askList,
									image: this.customer
								}
								this.msgList.push(obj);
							}
						} else {
							this.$tip.toast(res.data.message)
						}
					})
					this.chatMsg = '';
					this.scrollToBottom()
				} else {
					this.$modal.showToast('不能发送空白消息')
				}
				this.keywordNumber = 0;
			},
			//发送子项消息
			searchSubItem(param){
				this.$http.get(this.getSubItemUrl,{params:{subjectId:param}}).then(res=>{
					console.log("查询数据：",res);
					let subItemList = res.data.result;
					console.log("子项集合：",subItemList);
					let obj = {
						botContent: "子项数据",
						userContent: "",
						subItemArrary:subItemList,
						image: this.customer
					}
					this.msgList.push(obj);
				})
			},
			//跳转到办事指南
			toWork(param){
				console.log("办事指南跳转Id:",param);
			}
			
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			 //background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				//background-color:skyblue;
				height: auto;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
						// white-space: pre-line; 
					}

					.subjetItem {
						display: inline-block;//长度自适应
						border-bottom: 1rpx #4F7DF5 solid;
						margin: 10rpx 0;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						//background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chatBottom {
			width: 100%;
			height: 100rpx;
			display: flex;
			flex-direction: column;
			background-color: #fff;
			transition: all 0.1s ease;

			.workModel {
				background-color: #fff;
				border: 1rpx #8799a3 solid;
				border-radius: 10rpx;
				margin-right: 20rpx;
				padding: 5rpx 20rpx;
				font-size: 26rpx;
			}

			.inputText {
				flex: 1;
				display: flex;
				flex-direction: column;
				border-radius: 12rpx;
				border: 1rpx #8799a3 solid;
				padding: 0  10rpx;
				margin: 10rpx 0 10rpx 10rpx;
			}

			.placeholder {
				color: #8799a3;
				font-size: 28rpx;

			}

			.inputStyle {
				font-size: 28rpx;
				margin-top: 10rpx;
				width: auto;
				//height: 177rpx;
			}

			.send-btn {
				width: 150rpx;
				height: 60rpx;
				margin: 10rpx 10rpx;
				border-radius: 14rpx;
				background-color: #8dc63f;
				font-size: 28rpx;
			}
		}
	}
</style>